<template>
  <div>
    <h2 class="tab-title">订单管理</h2>
    
    <div class="filter-bar">
      <el-input 
        placeholder="搜索订单编号或客户信息..." 
        prefix-icon="Search" 
        v-model="searchKeyword" 
        class="search-input"
        @keyup.enter="handleSearch"
      />
      <el-select v-model="statusFilter" placeholder="订单状态" clearable @change="handleStatusChange">
        <el-option label="全部" value=""></el-option>
        <el-option label="待付款" value="PENDING"></el-option>
        <el-option label="已付款" value="PAID"></el-option>
        <el-option label="处理中" value="PROCESSING"></el-option>
        <el-option label="已发货" value="SHIPPED"></el-option>
        <el-option label="已送达" value="DELIVERED"></el-option>
        <el-option label="已取消" value="CANCELLED"></el-option>
        <el-option label="已退款" value="REFUNDED"></el-option>
      </el-select>
      <el-date-picker 
        v-model="dateRange" 
        type="daterange" 
        range-separator="至" 
        start-placeholder="开始日期" 
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
        @change="handleDateRangeChange"
      ></el-date-picker>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetFilters">重置</el-button>
    </div>
    
    <el-card shadow="hover" class="table-card">
      <el-table 
        :data="orders.content" 
        style="width: 100%" 
        border 
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="orderNumber" label="订单编号" width="150"></el-table-column>
        <el-table-column label="下单日期" width="170">
          <template #default="scope">
            {{ formatDateTime(scope.row.orderDate) }}
          </template>
        </el-table-column>
        <el-table-column label="客户信息" width="180">
          <template #default="scope">
            <div v-if="scope.row.customerId">
              {{ scope.row.customerId }}
              <el-button type="primary" link size="small" @click="loadCustomerInfo(scope.row.customerId)">
                查看详情
              </el-button>
            </div>
            <span v-else class="text-muted">未知客户</span>
          </template>
        </el-table-column>
        <el-table-column label="金额" width="120">
          <template #default="scope">
            ¥{{ formatPrice(scope.row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getChineseStatus(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="物流单号" width="150">
          <template #default="scope">
            <span v-if="scope.row.trackingNumber">{{ scope.row.trackingNumber }}</span>
            <span v-else class="text-muted">未发货</span>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" type="primary" @click="viewOrderDetail(scope.row)">查看</el-button>
            <el-button 
              size="small" 
              type="success" 
              v-if="scope.row.status === 'PAID' || scope.row.status === 'PROCESSING'"
              @click="handleShipOrder(scope.row)"
            >发货</el-button>
            <el-button 
              size="small" 
              type="danger"
              v-if="scope.row.status === 'PENDING' || scope.row.status === 'PAID' || scope.row.status === 'PROCESSING'"
              @click="handleCancelOrder(scope.row)"
            >取消</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="orders.totalElements"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 查看订单详情对话框 -->
    <el-dialog v-model="orderDetailVisible" title="订单详情" width="70%" destroy-on-close>
      <div v-if="currentOrder" class="order-detail">
        <div class="detail-header">
          <div class="order-info">
            <h3>订单号: {{ currentOrder.orderNumber }}</h3>
            <p>下单时间: {{ formatDateTime(currentOrder.orderDate) }}</p>
            <p>订单状态: <el-tag :type="getStatusType(currentOrder.status)">{{ getChineseStatus(currentOrder.status) }}</el-tag></p>
          </div>
          <div class="customer-info">
            <h4>客户信息</h4>
            <p>客户ID: {{ currentOrder.customerId }}</p>
            <p>收货地址: {{ currentOrder.shippingAddress }}</p>
            <el-button type="primary" size="small" @click="loadCustomerInfo(currentOrder.customerId)">
              查看客户详情
            </el-button>
          </div>
        </div>

        <el-divider content-position="left">商品信息</el-divider>
        
        <el-table :data="currentOrder.orderItems" border style="width: 100%">
          <el-table-column prop="productName" label="商品名称"></el-table-column>
          <el-table-column prop="productId" label="商品ID" width="120"></el-table-column>
          <el-table-column prop="sku" label="SKU" width="120"></el-table-column>
          <el-table-column label="图片" width="100">
            <template #default="scope">
              <el-image 
              preview-teleported="true"
                v-if="scope.row.productImage" 
                :src="scope.row.productImage" 
                :preview-src-list="[scope.row.productImage]"
                style="width: 50px; height: 50px"
              ></el-image>
              <span v-else>暂无图片</span>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
          <el-table-column label="单价" width="120">
            <template #default="scope">
              ¥{{ formatPrice(scope.row.unitPrice) }}
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="scope">
              ¥{{ formatPrice(scope.row.subtotal) }}
            </template>
          </el-table-column>
        </el-table>

        <div class="order-summary">
          <p><span>商品总额:</span> <span>¥{{ formatPrice(currentOrder.totalAmount - (currentOrder.shippingCost || 0) - (currentOrder.taxAmount || 0)) }}</span></p>
          <p v-if="currentOrder.shippingCost"><span>运费:</span> <span>¥{{ formatPrice(currentOrder.shippingCost) }}</span></p>
          <p v-if="currentOrder.taxAmount"><span>税费:</span> <span>¥{{ formatPrice(currentOrder.taxAmount) }}</span></p>
          <p class="total"><span>订单总额:</span> <span>¥{{ formatPrice(currentOrder.totalAmount) }}</span></p>
        </div>

        <el-divider content-position="left">物流信息</el-divider>
        
        <div class="shipping-info">
          <p>物流方式: {{ currentOrder.shippingMethod || '未指定' }}</p>
          <!-- <p>物流单号: {{ currentOrder.trackingNumber || '未发货' }}</p> -->
          <p v-if="currentOrder.shippingDate">发货时间: {{ formatDateTime(currentOrder.shippingDate) }}</p>
          <p v-if="currentOrder.deliveryDate">送达时间: {{ formatDateTime(currentOrder.deliveryDate) }}</p>
        </div>

        <div class="dialog-footer">
          <el-button @click="orderDetailVisible = false">关闭</el-button>
          <el-button 
            type="success" 
            v-if="currentOrder.status === 'PAID' || currentOrder.status === 'PROCESSING'"
            @click="handleShipOrder(currentOrder)"
          >发货</el-button>
          <el-button 
            type="danger"
            v-if="currentOrder.status === 'PENDING' || currentOrder.status === 'PAID' || currentOrder.status === 'PROCESSING'"
            @click="handleCancelOrder(currentOrder)"
          >取消订单</el-button>
        </div>
      </div>
      <div v-else class="loading-spinner">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>正在加载订单详情...</span>
      </div>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog v-model="shipOrderVisible" title="订单发货" width="500px" destroy-on-close>
      <el-form :model="shipForm" :rules="shipRules" ref="shipFormRef" label-width="100px">
        <el-form-item label="物流公司" prop="carrierName">
          <el-select v-model="shipForm.carrierName" placeholder="请选择物流公司">
            <el-option 
              v-for="carrier in availableCarriers" 
              :key="carrier.code" 
              :label="carrier.name" 
              :value="carrier.name">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="shipOrderVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShipOrder" :loading="processingShipment">确认发货</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 客户详情对话框 -->
    <el-dialog v-model="customerInfoVisible" title="客户详细信息" width="50%" destroy-on-close append-to-body>
      <div v-if="customerInfo" class="customer-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="客户ID">{{ customerInfo.customerId }}</el-descriptions-item>
          <el-descriptions-item label="用户名" v-if="customerInfo.username && customerInfo.username !== '正在加载...'">{{ customerInfo.username }}</el-descriptions-item>
          <el-descriptions-item label="姓名" v-if="customerInfo.fullName || customerInfo.name">{{ customerInfo.fullName || customerInfo.name }}</el-descriptions-item>
          <el-descriptions-item label="电子邮件" v-if="customerInfo.email">{{ customerInfo.email }}</el-descriptions-item>
          <el-descriptions-item label="电话" v-if="customerInfo.phone">{{ customerInfo.phone }}</el-descriptions-item>
          <el-descriptions-item label="注册时间" v-if="customerInfo.createdAt || customerInfo.createTime">{{ formatDateTime(customerInfo.createdAt || customerInfo.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="收货地址">{{ customerInfo.address || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="账单地址" v-if="customerInfo.billingAddress">{{ customerInfo.billingAddress }}</el-descriptions-item>
          <el-descriptions-item label="首选支付方式" v-if="customerInfo.paymentMethod">{{ customerInfo.paymentMethod }}</el-descriptions-item>
          <!-- <el-descriptions-item label="备注" v-if="customerInfo.note">
            <el-tag v-if="customerInfo.note.includes('成功')" type="success">{{ customerInfo.note }}</el-tag>
            <el-tag v-else-if="customerInfo.note.includes('失败')" type="warning">{{ customerInfo.note }}</el-tag>
            <span v-else>{{ customerInfo.note }}</span>
          </el-descriptions-item> -->
        </el-descriptions>
      </div>
      <div v-else class="loading-spinner">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>正在加载客户信息...</span>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';
import { getOrdersPage, getOrderById, updateOrderStatus, updateTrackingNumber, searchOrders, getOrdersByStatus, getOrdersByDateRange, getAvailableCarriers, createOrderShipment } from '../../api/order';
import { getCustomerById } from '../../api/customer';

// 数据和状态
const loading = ref(true);
const searchKeyword = ref('');
const statusFilter = ref('');
const dateRange = ref(null);
const currentPage = ref(1);
const pageSize = ref(10);
const orders = ref({
  content: [],
  totalElements: 0,
  totalPages: 0,
  size: 10,
  number: 0
});

// 订单详情
const orderDetailVisible = ref(false);
const currentOrder = ref(null);

// 发货对话框
const shipOrderVisible = ref(false);
const shipForm = reactive({
  orderId: null,
  carrierName: ''
});
const shipRules = {
  carrierName: [{ required: true, message: '请选择物流公司', trigger: 'change' }]
};
const shipFormRef = ref(null);
const processingShipment = ref(false);
const availableCarriers = ref([]);

// 客户信息相关
const customerInfoVisible = ref(false);
const customerInfo = ref(null);
const loadingCustomerInfo = ref(false);

// 初始化加载
onMounted(() => {
  fetchOrders();
});

// 加载订单数据
const fetchOrders = async () => {
  loading.value = true;
  try {
    const res = await getOrdersPage(currentPage.value - 1, pageSize.value);
    orders.value = res.data;
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('获取订单列表失败');
  } finally {
    loading.value = false;
  }
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchOrders();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchOrders();
};

// 搜索和过滤
const handleSearch = async () => {
  loading.value = true;
  currentPage.value = 1;
  
  try {
    if (searchKeyword.value) {
      const res = await searchOrders(searchKeyword.value, 0, pageSize.value);
      orders.value = res.data;
    } else if (statusFilter.value && dateRange.value) {
      // 状态和日期范围都有
      // 这里需要后端支持组合查询，如果不支持，可以使用状态查询然后前端筛选日期
      const res = await getOrdersByStatus(statusFilter.value, 0, pageSize.value);
      orders.value = res.data;
    } else if (statusFilter.value) {
      // 只有状态
      const res = await getOrdersByStatus(statusFilter.value, 0, pageSize.value);
      orders.value = res.data;
    } else if (dateRange.value) {
      // 只有日期范围
      const res = await getOrdersByDateRange(
        dateRange.value[0], 
        dateRange.value[1], 
        0, 
        pageSize.value
      );
      orders.value = res.data;
    } else {
      // 没有任何过滤，获取全部
      await fetchOrders();
    }
  } catch (error) {
    console.error('搜索订单失败:', error);
    ElMessage.error('搜索订单失败');
  } finally {
    loading.value = false;
  }
};

const handleStatusChange = () => {
  handleSearch();
};

const handleDateRangeChange = () => {
  if (dateRange.value) {
    handleSearch();
  }
};

const resetFilters = () => {
  searchKeyword.value = '';
  statusFilter.value = '';
  dateRange.value = null;
  currentPage.value = 1;
  fetchOrders();
};

// 查看订单详情
const viewOrderDetail = async (order) => {
  orderDetailVisible.value = true;
  currentOrder.value = null;
  
  try {
    const res = await getOrderById(order.id);
    currentOrder.value = res.data;
  } catch (error) {
    console.error('获取订单详情失败:', error);
    ElMessage.error('获取订单详情失败');
    orderDetailVisible.value = false;
  }
};

// 发货处理
const handleShipOrder = async (order) => {
  shipForm.orderId = order.id;
  shipForm.carrierName = '';
  
  try {
    // 获取可用承运商列表
    const response = await getAvailableCarriers();
    if (response.code === 200) {
      availableCarriers.value = response.data || [];
    } else {
      availableCarriers.value = [];
      ElMessage.warning('无法获取物流承运商列表');
    }
  } catch (error) {
    console.error('获取承运商列表失败:', error);
    availableCarriers.value = [];
    ElMessage.warning('加载物流承运商失败');
  }
  
  shipOrderVisible.value = true;
};

const confirmShipOrder = async () => {
  if (!shipFormRef.value) return;
  
  await shipFormRef.value.validate(async (valid) => {
    if (valid) {
      processingShipment.value = true;
      
      try {
        // 调用创建物流单接口
        const result = await createOrderShipment(shipForm.orderId, shipForm.carrierName);
        
        if (result.code === 200) {
          ElMessage.success('订单已发货');
          shipOrderVisible.value = false;
          
          // 刷新订单列表
          fetchOrders();
          
          // 如果当前正在查看该订单详情，刷新详情
          if (orderDetailVisible.value && currentOrder.value && currentOrder.value.id === shipForm.orderId) {
            viewOrderDetail({ id: shipForm.orderId });
          }
        } else {
          ElMessage.error(result.message || '发货失败');
        }
      } catch (error) {
        console.error('发货失败:', error);
        ElMessage.error('发货失败，请稍后重试');
      } finally {
        processingShipment.value = false;
      }
    }
  });
};

// 取消订单
const handleCancelOrder = (order) => {
  ElMessageBox.confirm('确定要取消该订单吗？此操作不可逆', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateOrderStatus(order.id, 'CANCELLED');
      ElMessage.success('订单已取消');
      
      // 刷新订单列表
      fetchOrders();
      
      // 如果当前正在查看该订单详情，刷新详情
      if (orderDetailVisible.value && currentOrder.value && currentOrder.value.id === order.id) {
        viewOrderDetail({ id: order.id });
      }
    } catch (error) {
      console.error('取消订单失败:', error);
      ElMessage.error('取消订单失败');
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 加载客户信息
const loadCustomerInfo = async (customerId) => {
  if (!customerId) {
    ElMessage.error('缺少客户ID，无法获取客户信息');
    return;
  }
  
  customerInfoVisible.value = true;
  customerInfo.value = null;
  loadingCustomerInfo.value = true;
  
  // 先显示基本信息
  customerInfo.value = {
    customerId: customerId,
    username: '正在加载...',
    address: '正在加载...'
  };
  
  try {
    // 尝试从订单数据中获取收货地址等基本信息
    const orderWithCustomer = orders.value.content.find(o => o.customerId === customerId);
    if (orderWithCustomer) {
      customerInfo.value = {
        customerId: customerId,
        address: orderWithCustomer.shippingAddress || '未设置',
        billingAddress: orderWithCustomer.billingAddress,
        paymentMethod: orderWithCustomer.paymentMethod
      };
    }
    
    // 再尝试从用户服务获取更多信息
    try {
      const res = await getCustomerById(customerId);
      
      if (res.code === 200 && res.data) {
        // 合并信息，保留之前的地址信息
        customerInfo.value = {
          ...res.data,
          address: res.data.address || customerInfo.value.address || '未设置',
          billingAddress: res.data.billingAddress || customerInfo.value.billingAddress,
          note: '用户信息获取成功'
        };
      }
    } catch (userError) {
      console.warn('获取用户详情失败，使用基本信息:', userError);
      // 不改变已有的基本客户信息
      customerInfo.value = {
        ...customerInfo.value,
        note: '只能显示订单中的基本信息，无法获取详细用户信息'
      };
    }
  } catch (error) {
    console.error('获取客户信息异常:', error);
    ElMessage.error('获取客户信息失败，请检查网络或服务状态');
    
    // 保持基本信息
    customerInfo.value = {
      customerId: customerId,
      note: '获取详细信息失败，请检查服务状态'
    };
  } finally {
    loadingCustomerInfo.value = false;
  }
};

// 工具函数
const formatDateTime = (dateString) => {
  if (!dateString) return '未知';
  
  try {
    // 处理Java LocalDateTime序列化为数组的情况
    if (Array.isArray(dateString)) {
      // 如果是[year, month, day, hour, minute, second]格式
      const [year, month, day, hour=0, minute=0, second=0] = dateString;
      // 注意JavaScript月份是0-11，所以需要-1
      return new Date(year, month-1, day, hour, minute, second)
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
    }
    
    // 尝试直接解析日期字符串
    const date = new Date(dateString);
    if (isNaN(date.getTime())) {
      // 尝试解析ISO格式
      const isoDate = new Date(dateString.replace(' ', 'T'));
      if (isNaN(isoDate.getTime())) {
        console.warn('无法解析日期:', dateString);
        return dateString; // 返回原始字符串
      }
      return isoDate.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    }
    
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (e) {
    console.error('日期格式化错误:', e);
    return dateString; // 出错时返回原始字符串
  }
};

const formatPrice = (price) => {
  if (!price) return '0.00';
  return Number(price).toFixed(2);
};

const getStatusType = (status) => {
  const statusMap = {
    'PENDING': 'warning',
    'PAID': 'primary',
    'PROCESSING': 'info',
    'SHIPPED': 'success',
    'DELIVERED': 'success',
    'CANCELLED': 'danger',
    'REFUNDED': 'danger'
  };
  return statusMap[status] || 'info';
};

const getChineseStatus = (status) => {
  const statusMap = {
    'PENDING': '待付款',
    'PAID': '已付款',
    'PROCESSING': '处理中',
    'SHIPPED': '已发货',
    'DELIVERED': '已送达',
    'CANCELLED': '已取消',
    'REFUNDED': '已退款'
  };
  return statusMap[status] || status;
};
</script>

<style scoped>
.tab-title {
  margin-top: 0;
  margin-bottom: 20px;
  color: #303133;
  font-weight: bold;
  position: relative;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.tab-title:after {
  content: '';
  display: block;
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 50px;
  height: 3px;
  background-color: #67C23A;
}

.filter-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: center;
}

.search-input {
  width: 300px;
}

.table-card {
  border-radius: 8px;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.text-muted {
  color: #909399;
  font-size: 0.9em;
}

/* 订单详情样式 */
.order-detail {
  padding: 0 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.order-info, .customer-info {
  flex: 1;
}

.order-info h3 {
  margin-top: 0;
}

.customer-info {
  border-left: 1px solid #ebeef5;
  padding-left: 20px;
}

.customer-info h4 {
  margin-top: 0;
}

.order-summary {
  margin-top: 20px;
  text-align: right;
}

.order-summary p {
  display: flex;
  justify-content: flex-end;
  margin: 5px 0;
}

.order-summary p span:first-child {
  margin-right: 20px;
  color: #606266;
}

.order-summary .total {
  font-weight: bold;
  font-size: 1.1em;
  margin-top: 10px;
}

.shipping-info {
  margin: 15px 0;
}

.loading-spinner {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  flex-direction: column;
}

.loading-spinner .el-icon {
  font-size: 30px;
  margin-bottom: 10px;
}

.dialog-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-input {
    width: 100%;
  }
  
  .detail-header {
    flex-direction: column;
  }
  
  .customer-info {
    border-left: none;
    border-top: 1px solid #ebeef5;
    padding-left: 0;
    padding-top: 20px;
    margin-top: 20px;
  }
}

/* 客户详情样式 */
.customer-detail {
  padding: 20px;
}
</style> 